﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text;
using System.Threading;
using System.Collections.Generic;

namespace WindowsPhoneApplication1.Connectors
{
    public class UpdatesConnector : Connector
    {
        public static void GetBliposphere()
        {
            ThreadPool.QueueUserWorkItem(q =>
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ApiUrl + "bliposphere");
                    req.Method = "GET";
                    req.Headers["X-Blip-API"] = "0.02";
                    req.Accept = "application/json";

                    req.BeginGetResponse(new AsyncCallback(
                        delegate(IAsyncResult asynchronousResult)
                        {
                            HttpStatusCode statusCode;
                            string resultString = "";

                            if (!req.HaveResponse)
                            {
                                throw new WebException();
                            }

                            try
                            {
                                using (HttpWebResponse resp = (HttpWebResponse)((HttpWebRequest)asynchronousResult.AsyncState).EndGetResponse(asynchronousResult))
                                {
                                    using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
                                    {
                                        resultString = sr.ReadToEnd();
                                        statusCode = resp.StatusCode;
                                        sr.ReadToEnd();
                                        sr.Close();
                                    }
                                }
                            }
                            catch
                            {
                                statusCode = HttpStatusCode.GatewayTimeout;
                            }

                            if (statusCode == HttpStatusCode.OK)
                            {
                                try
                                {
                                    List<WebServiceDataSources.Status> statuses = new List<WebServiceDataSources.Status>();
                                    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resultString)))
                                    {
                                        var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(statuses.GetType());
                                        statuses = ser.ReadObject(ms) as List<WebServiceDataSources.Status>;

                                        if (Snlp != null)
                                        {
                                            Snlp.UpdateBliposphereDataSource(statuses);
                                        }
                                        else if (Alpp != null)
                                            Alpp.UpdateBliposphereDataSource(statuses);
                                    }
                                }
                                catch (Exception e)
                                {
                                    e.ToString();
                                    GetBliposphere();
                                }
                            }
                        }), req);
                });
        }

        public static void GetUserUpdates()
        {
            ThreadPool.QueueUserWorkItem(q =>
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ApiUrl + "dashboard");
                req.Method = "GET";
                req.Headers["X-Blip-API"] = "0.02";
                req.Accept = "application/json";

                AppendAuthHeader(req);

                req.BeginGetResponse(new AsyncCallback(
                    delegate(IAsyncResult asynchronousResult)
                    {
                        HttpStatusCode statusCode;
                        string resultString = "";

                        if (!req.HaveResponse)
                        {
                            throw new WebException();
                        }

                        try
                        {
                            using (HttpWebResponse resp = (HttpWebResponse)((HttpWebRequest)asynchronousResult.AsyncState).EndGetResponse(asynchronousResult))
                            {
                                using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
                                {
                                    resultString = sr.ReadToEnd();
                                    statusCode = resp.StatusCode;
                                    sr.ReadToEnd();
                                    sr.Close();
                                }
                            }
                        }
                        catch
                        {
                            statusCode = HttpStatusCode.GatewayTimeout;
                        }

                        if (statusCode == HttpStatusCode.OK)
                        {
                            try
                            {
                                List<WebServiceDataSources.Status> statuses = new List<WebServiceDataSources.Status>();
                                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resultString)))
                                {
                                    var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(statuses.GetType());
                                    statuses = ser.ReadObject(ms) as List<WebServiceDataSources.Status>;

                                    if (Alpp != null)
                                    {
                                        Alpp.UpdateUpdatesDataSource(statuses);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                e.ToString();
                                GetBliposphere();
                            }
                        }
                    }), req);
            });
        }

        public static void PostUpdate(string s, string photo)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ApiUrl + "updates");
            req.Method = "POST";
            req.Headers["X-Blip-API"] = "0.02";
            req.Accept = "application/json";

            AppendAuthHeader(req);

            HttpStatusCode statusCode;
            string resultString;

            req.BeginGetRequestStream(new AsyncCallback(
                delegate(IAsyncResult asynchronousResult)
                {
                    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

                    using (Stream str= request.EndGetRequestStream(asynchronousResult))
                    {
                        byte[] byteParameters;
                        
                        if (photo == null)
                            byteParameters = Encoding.UTF8.GetBytes("update[body]=" + s);
                        else
                            byteParameters = Encoding.UTF8.GetBytes(/*"update[body]=" + s + */"update[picture]=" + photo);

                        str.Write(byteParameters, 0, byteParameters.GetLength(0));
                        str.Close();

                        //IAsyncResult result;
                        try
                        {
                            //result =
                            request.BeginGetResponse(new AsyncCallback(
                                delegate(IAsyncResult result)
                                {
                                    try
                                    {

                                        if (request.HaveResponse == false)
                                            throw new WebException();

                                        HttpWebRequest req2 = (HttpWebRequest)result.AsyncState;

                                        try
                                        {
                                            using (HttpWebResponse resp = (HttpWebResponse)req2.EndGetResponse(result))
                                            {
                                                //if (resp.Headers[HttpRequestHeader.Expires] != null)
                                                    //dt = DateTime.Parse(resp.Headers[HttpRequestHeader.Expires]);
                                                using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
                                                {
                                                    resultString = sr.ReadToEnd();
                                                    statusCode = resp.StatusCode;
                                                    //sr.ReadToEnd();
                                                    sr.Close();
                                                }
                                                resp.Close();
                                            }
                                        }
                                        catch (WebException e)
                                        {
                                            statusCode = ((HttpWebResponse)(e.Response)).StatusCode;
                                        }
                                    }
                                    catch
                                    {
                                        statusCode = HttpStatusCode.GatewayTimeout;
                                    }

                                    if (statusCode == HttpStatusCode.Created)
                                    {
                                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                                        {
                                            MessageBox.Show("Wiadomość wysłana poprawnie.");
                                            //todo: clean textboxes
                                        });
                                    }
                                    else
                                    {
                                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                                            {
                                                MessageBox.Show("Błąd przy dodawaniu wiadomości. Spróbuj ponownie.");
                                            });
                                    }
                                }), req);

                        }
                        catch
                        {
                            statusCode = HttpStatusCode.GatewayTimeout;
                        }
                    }
                }), req);
        }
    }
}
